package cn.stronglink.esm27.collection.iot.devices.esm27.request.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.stronglink.esm27.collection.core.message.IMessageHandle;
import cn.stronglink.esm27.collection.core.util.ContextUtils;
import cn.stronglink.esm27.collection.iot.devices.esm27.message.MQMessageOfESM27;
import cn.stronglink.esm27.collection.mq.TopicSender;
import io.netty.channel.ChannelHandlerContext;

/**
 * 通用抽象处理类
 * @author yuzhantao
 *
 */
public abstract class AbstractHandle implements IMessageHandle<MQMessageOfESM27, Object> {
	protected static Logger logger = LogManager.getLogger(CallHandle.class.getName());
	protected TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	protected final static String TOPIC_NAME="ESM27ToService";		// MQ发送主题
	
	/**
	 * 获取激活码
	 * @return
	 */
	protected abstract String getActionCode();
	/**
	 * 处理消息
	 * @param t
	 * @throws Exception 
	 */
	protected abstract void handleMessage(MQMessageOfESM27 t) throws Exception;
	
	@Override
	public boolean isHandle(MQMessageOfESM27 t) {
		if (t.getActioncode().equals(this.getActionCode())) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessageOfESM27 t) {
		try {
			this.handleMessage(t);
		} catch (Exception e) {
			logger.error(e);
			try {
				this.sendExceptionMessage(e);
			}catch(Exception err) {
				err.printStackTrace();
			}
		}
		return null;
	}
	
	protected String getActionCodeReturn() {
		return this.getActionCode()+"Return";
	}
	
	/**
	 * 发送异常信息到MQ
	 * @param e
	 */
	protected void sendExceptionMessage(Exception e) {
		MQMessageOfESM27 message = new MQMessageOfESM27();
		message.setActioncode(this.getActionCodeReturn());
		message.setTimeStamp(System.currentTimeMillis());
		message.setAwsPostdata(null);
		message.setIsSuccess(false);
		message.setErrorMessage(e.getMessage());
		
		String json = JSON.toJSONString(message);
		topicSender.send(TOPIC_NAME, json);
		logger.info("发送[{}]到MQ完成:{}","异常反馈信息",json);
	}
	
	/**
	 * 发送正常信息到MQ
	 * @param datas		需要传送到MQ的数据段
	 */
	protected void sendReturnMessage(Object datas) {
		MQMessageOfESM27 message = new MQMessageOfESM27();
		message.setActioncode(this.getActionCodeReturn());
		message.setTimeStamp(System.currentTimeMillis());
		message.setAwsPostdata(datas);
		message.setIsSuccess(true);
		
		String json = JSON.toJSONString(message);
		topicSender.send(TOPIC_NAME, json);
		logger.info("发送[{}]到MQ完成:{}","反馈信息",json);
	}
}
